//
//  NewDownloadViewController.m
//  Everest
//
//  Created by 李其昌 on 15/1/1.
//  Copyright (c) 2015年 ThreeL. All rights reserved.
//

#import "NewDownloadViewController.h"
#import "FilesDownManage.h"
#import "DownloadDelegate.h"
#import "FileModel.h"
#import "MyNavigationView.h"
#import "NewDownloadCell.h"
#import "FinishedCell.h"
#import "PlayViewController.h"
#import "AvReadioPlayer.h"

#import "MyNavigationView.h"

#define kDownloadReuse @"download"
#define kFinishedReuse @"finished"
#define kDocPath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]

@interface NewDownloadViewController ()<UITableViewDataSource, UITableViewDelegate, DownloadDelegate>
// 下载的tableView
@property (nonatomic, retain) UITableView *downloadingTable;
// 完成下载的tableView
@property (nonatomic, retain) UITableView *finishedTable;
// 下载列表
@property (nonatomic, retain) NSMutableArray *downloadingList;
// 完成列表
@property (nonatomic, retain) NSMutableArray *finishedList;
// 没有下载任务时显示的label
@property (nonatomic, retain) UILabel *noLoadsInfo;
// 正在下载视图的按钮
@property (nonatomic, retain) UIButton *downloadingViewBtn;
// 完成下载视图的按钮
@property (nonatomic, retain) UIButton *finieshedViewBtn;
// 自定义导航控制器
@property (nonatomic, retain) MyNavigationView *nav;

@property (nonatomic, retain) NSString *documentFolder;
@property (nonatomic, retain) NSString *audioFolder;
@property (nonatomic, retain) UILabel *diskLabel;

@end

@implementation NewDownloadViewController

- (void)dealloc
{
    [_diskLabel release];
    [_audioFolder release];
    [_documentFolder release];
    [_nav release];
    [_finieshedViewBtn release];
    [_downloadingViewBtn release];
    [_noLoadsInfo release];
    [_finishedList release];
    [_downloadingList release];
    [_finishedTable release];
    [_downloadingTable release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
//        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
//        [center addObserver:self selector:@selector(receiveNotification:) name:@"value" object:nil];
    }
    return self;
}
//// 通知中心, 如果用户登陆, 则创建文件夹
//- (void)receiveNotification:(NSNotification *)noti
//{
//    NSLog(@"%@",noti.object);
//    
//    NSString *str = [NSString stringWithFormat:@"%@",noti.object];
//    [FilesDownManage sharedFilesDownManageWithBasepath:str TargetPathArr:[NSArray arrayWithObject:@"DownLoad/mp3"]];
//    self.documentFolder = [kDocPath stringByAppendingFormat:@"/%@", str];
//    NSFileManager *fileManager = [NSFileManager defaultManager];
//    self.audioFolder = [self.documentFolder stringByAppendingFormat:@"/audio"];
//    NSError *error = nil;
//    BOOL result = [fileManager createDirectoryAtPath:self.audioFolder withIntermediateDirectories:YES attributes:nil error:&error];
//    if (result) {
//        NSLog(@"文件夹创建成功");
//    } else {
//        NSLog(@"文件夹创建失败");
//    }
//    NSLog(@"%@", kDocPath);
//}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // 签订下载代理
    [FilesDownManage sharedFilesDownManage].downloadDelegate = self;
    // 隐藏导航控制器
    self.navigationController.navigationBarHidden = YES;
    // 自定义导航控制器
    self.nav = [[MyNavigationView alloc] initWithFrame:CGRectMake(-1, -1, self.view.bounds.size.width + 1, 65)];
    [self.view addSubview:self.nav];
    
    // 设置正在下载视图和已完成视图的两个按钮
    [self setDownloadButton];
    [self setFinieshedButton];
    // 设置正在下载的tableView
    [self setDownloadingTable];
    // 设置完成下载的tableView
    [self setFinishedTable];
    // 设置没有任务时文字提示
    [self setNoLoadsInfo];
    // 设置默认显示样式
    [self setDefaultStyles];
    // 显示剩余空间大小
    [self setDiskSpace];
}

- (void)setDiskSpace
{
    self.diskLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 64, self.view.bounds.size.width, 20)];
    self.diskLabel.backgroundColor = [UIColor lightGrayColor];
    self.diskLabel.font = [UIFont systemFontOfSize:12];
    self.diskLabel.textAlignment = NSTextAlignmentCenter;
    self.diskLabel.textColor = [UIColor whiteColor];
    self.diskLabel.text = [CommonHelper getDiskSpaceInfo];
    [self.view addSubview:self.diskLabel];
    [_diskLabel release];
}

// 视图将要显示时
- (void)viewWillAppear:(BOOL)animated
{
    
        FilesDownManage *filedownmanage = [FilesDownManage sharedFilesDownManage];
        [filedownmanage startLoad];
        self.downloadingList = filedownmanage.downinglist;
        [self.downloadingTable reloadData];
        self.finishedList = filedownmanage.finishedlist;
        [self.finishedTable reloadData];
        NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSLog(@"%@", docPath);
    
}

- (void)viewDidUnload
{
    
    [self setDownloadingViewBtn:nil];
    [self setFinieshedViewBtn:nil];
    [self setNoLoadsInfo:nil];
    self.downloadingTable = nil;
    self.finishedTable = nil;
    [super viewDidUnload];
}

// 视图
- (void)viewWillDisappear:(BOOL)animated
{
    // self.navigationController.navigationBar.hidden = NO;
    FilesDownManage *filedownmanage = [FilesDownManage sharedFilesDownManage];
    [filedownmanage saveFinishedFile];
    
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

// 设置没有任务时的文字提示
- (void)setNoLoadsInfo
{
    self.noLoadsInfo = [[UILabel alloc] initWithFrame:CGRectMake(self.view.bounds.size.width * 0.15, self.view.bounds.size.height * 0.375, self.view.bounds.size.width * 0.72, self.view.bounds.size.height * 0.04)];
    self.noLoadsInfo.text = @"您还没有任何下载任务哟!";
    self.noLoadsInfo.textColor = [UIColor lightGrayColor];
    self.noLoadsInfo.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.noLoadsInfo];
    [_noLoadsInfo release];
}

// 设置默认显示样式
- (void)setDefaultStyles
{
    self.downloadingTable.hidden = NO;
    self.finishedTable.hidden =YES;
    self.finieshedViewBtn.selected = NO;
    self.downloadingViewBtn.selected = YES;
}

// 设置下载按钮
- (void)setDownloadButton
{
    self.downloadingViewBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.downloadingViewBtn.frame = CGRectMake(0, 0, self.view.bounds.size.width / 4, 30);
    self.downloadingViewBtn.center = CGPointMake(self.view.bounds.size.width / 4, 40);
    [self.downloadingViewBtn setTitle:@"正在下载" forState:UIControlStateNormal];
    [self.downloadingViewBtn setTitleColor:[UIColor colorWithRed:68 / 255.0 green:150 / 255.0 blue:232 / 255.0 alpha:1] forState:UIControlStateHighlighted];
    [self.downloadingViewBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [self.downloadingViewBtn setTitleColor:[UIColor colorWithRed:68 / 255.0 green:150 / 255.0 blue:232 / 255.0 alpha:1] forState:UIControlStateSelected];
    [self.downloadingViewBtn addTarget:self action:@selector(downloadingButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.nav addSubview:self.downloadingViewBtn];
}

- (void)downloadingButton:(UIButton *)button
{
    NSLog(@"正在下载");
    self.downloadingTable.hidden = NO;
    self.finishedTable.hidden =YES;
//    clearallbtn.hidden = YES;
    self.finieshedViewBtn.selected = NO;
    self.downloadingViewBtn.selected = YES;
    [self.downloadingTable reloadData];
}
// 设置完成按钮
- (void)setFinieshedButton
{
    self.finieshedViewBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.finieshedViewBtn.frame = CGRectMake(0, 0, self.view.bounds.size.width / 4, 30);
    self.finieshedViewBtn.center = CGPointMake(self.view.bounds.size.width / 4 * 3, 40);
    [self.nav addSubview:self.finieshedViewBtn];
    [self.finieshedViewBtn setTitle:@"已完成" forState:UIControlStateNormal];
    [self.finieshedViewBtn setTitleColor:[UIColor colorWithRed:68 / 255.0 green:150 / 255.0 blue:232 / 255.0 alpha:1] forState:UIControlStateHighlighted];
    [self.finieshedViewBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [self.finieshedViewBtn setTitleColor:[UIColor colorWithRed:68 / 255.0 green:150 / 255.0 blue:232 / 255.0 alpha:1] forState:UIControlStateSelected];
    [self.finieshedViewBtn addTarget:self action:@selector(finieshedButton:) forControlEvents:UIControlEventTouchUpInside];
}

// 点击完成按钮触发方法
- (void)finieshedButton:(UIButton *)button
{
    self.downloadingTable.hidden = YES;
    self.finishedTable.hidden = NO;
//    clearallbtn.hidden = NO;
    self.finieshedViewBtn.selected = YES;
    self.downloadingViewBtn.selected = NO;
    [self.finishedTable reloadData];
    self.noLoadsInfo.hidden = YES;
}

// 设置正在下载的tableView
- (void)setDownloadingTable
{
    self.downloadingTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 84, self.view.bounds.size.width, self.view.bounds.size.height) style:UITableViewStylePlain];
    self.downloadingTable.dataSource = self;
    self.downloadingTable.delegate = self;
    self.downloadingTable.contentInset = UIEdgeInsetsMake(0, 0, 84 + 49, 0);
    [self.view addSubview:self.downloadingTable];
    [self.downloadingTable setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_downloadingTable release];
    [self.downloadingTable registerClass:[NewDownloadCell class] forCellReuseIdentifier:kDownloadReuse];
}
// 设置完成下载的tableView
- (void)setFinishedTable
{
    self.finishedTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 84, self.view.bounds.size.width, self.view.bounds.size.height) style:UITableViewStylePlain];
    self.finishedTable.dataSource = self;
    self.finishedTable.delegate = self;
    [self.view addSubview:self.finishedTable];
    self.finishedTable.contentInset = UIEdgeInsetsMake(0, 0, 84 + 49, 0);
    [self.finishedTable setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_finishedTable release];
    [self.finishedTable registerClass:[FinishedCell class] forCellReuseIdentifier:kFinishedReuse];
}

- (void)playAction:(UIButton *)button
{
    NSLog(@"播放");
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    FileModel *fileInfo = [self.finishedList objectAtIndex:button.tag];
    PlayViewController *playVC = [PlayViewController defaultPlayVC];
    playVC.avPlayer = [AvReadioPlayer defaultAvPlayer];
//    playVC.albumPlay = nil;
    playVC.album = nil;
    playVC.hotPlay = nil;
    playVC.focusFetail = nil;
    [playVC.albumArr removeAllObjects];
    [playVC.focusFetailArr removeAllObjects];
    [playVC.hotPlayArr removeAllObjects];
    
    if ([fileInfo.fileName hasSuffix:@"aac"]) {
        NSString *filePath = [docPath stringByAppendingFormat: @"/Download/aac/%@", fileInfo.fileName];
        NSURL *url = [NSURL fileURLWithPath:filePath];
        [playVC.avPlayer playWithUrl:url];
        playVC.fileInfo = fileInfo;
        playVC.nav.label.text = fileInfo.fileName;
        [playVC.myImageView setImage:[UIImage imageNamed:@"15.jpg"]];
        [self presentViewController:playVC animated:YES completion:^{
            
        }];

    } else if ([fileInfo.fileName hasSuffix:@"mp3"]) {
        NSString *filePath = [docPath stringByAppendingFormat: @"/Download/mp3/%@", fileInfo.fileName];
        NSURL *url = [NSURL fileURLWithPath:filePath];
        [playVC.avPlayer playWithUrl:url];
        playVC.fileInfo = fileInfo;
        playVC.nav.label.text = fileInfo.fileName;
        [playVC.myImageView setImage:[UIImage imageNamed:@"15.jpg"]];
        [self presentViewController:playVC animated:YES completion:^{
            
        }];
    }
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // 如果tableView为下载的tableView
    if (tableView == self.downloadingTable) {
        // 判断下载数组的长度
        if (self.downloadingList.count == 0) {
            // 判断下载的tableView是否隐藏
            if (self.downloadingTable.hidden) {
                // 如果是就把您还没有任何下载隐藏
                self.noLoadsInfo.hidden = YES;
            } else {
                // 如果不是就显示出您没有任何下载
                self.noLoadsInfo.hidden = NO;
            }
        } else {
            // 如果不是就把您还没有任何下载隐藏
            self.noLoadsInfo.hidden = YES;
        }
        // 返回正在下载数组的长度
        return [self.downloadingList count];
//        return 1;
    } else {
        // 返回完成下载的长度
        return [self.finishedList count];
//        return 1;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.downloadingTable) {
        NewDownloadCell *cell = [tableView dequeueReusableCellWithIdentifier:kDownloadReuse];
        cell.contentView.frame = CGRectMake(0, 0, kCellWidth, 80);
        cell.delegate = self;
        [cell.progressView setTrackImage:[UIImage imageNamed:@"下载管理进度条背景.png"]];
        [cell.progressView setProgressImage:[UIImage imageNamed:@"下载管理进度背景点九.png"]];
        
        
        ASIHTTPRequest *theRequest=[self.downloadingList objectAtIndex:indexPath.row];
        if (theRequest == nil) {
            return cell = Nil;
        }
        FileModel *fileInfo = [theRequest.userInfo objectForKey:@"File"];
        NSString *currentsize = [CommonHelper getFileSizeString:fileInfo.fileReceivedSize];
        NSString *totalsize = [CommonHelper getFileSizeString:fileInfo.fileSize];
        cell.fileName.text=fileInfo.fileName;
        cell.fileCurrentSize.text=currentsize;
        if ([totalsize longLongValue]<=0) {
            cell.fileSize.text=@"未知";
        }else
            cell.fileSize.text=[NSString stringWithFormat:@"大小:%@",totalsize];
        // cell.sizeinfoLab.text = [NSString stringWithFormat:@"%@/%@",currentsize,totalsize];
        cell.fileInfo=fileInfo;
        cell.request=theRequest;
        cell.fileType.text  =[NSString stringWithFormat:@"格式:%@",fileInfo.fileType] ;
//        cell.timelable.text =[NSString stringWithFormat:@"%@",fileInfo.time] ;
//        cell.timelable.hidden = YES;
        cell.fileImage.image = fileInfo.fileimage;//[self getImage:fileInfo];
        
        if ([currentsize longLongValue] == 0) {
            [cell.progressView setProgress:0.0f];
        }else
            [cell.progressView setProgress:[CommonHelper getProgress:[fileInfo.fileSize longLongValue] currentSize:[fileInfo.fileReceivedSize longLongValue]]];
        cell.sizePercentage.text = [NSString stringWithFormat:@"%0.0f%@", 100*(cell.progressView.progress),@"%"];
        // NSLog(@"process:%@",cell.sizeinfoLab.text);
        if(fileInfo.isDownloading)//文件正在下载
        {
            [cell.operateButton setBackgroundImage:[UIImage imageNamed:@"下载管理-暂停按钮.png"] forState:UIControlStateNormal];
        }
        else if(!fileInfo.isDownloading && !fileInfo.willDownloading&&!fileInfo.error)
        {
            [cell.operateButton setBackgroundImage:[UIImage imageNamed:@"下载管理-开始按钮.png"] forState:UIControlStateNormal];
            cell.sizePercentage.text = @"暂停";
        }else if(!fileInfo.isDownloading && fileInfo.willDownloading&&!fileInfo.error)
        {
            [cell.operateButton setBackgroundImage:[UIImage imageNamed:@"下载管理-开始按钮.png"] forState:UIControlStateNormal];
            cell.sizePercentage.text = @"等待";
        }else if (fileInfo.error)
        {
            [cell.operateButton setBackgroundImage:[UIImage imageNamed:@"下载管理-开始按钮.png"] forState:UIControlStateNormal];
            cell.sizePercentage.text = @"错误";
        }
        return cell;

    } else {
        FinishedCell *cell = [tableView dequeueReusableCellWithIdentifier:kFinishedReuse];
        cell.delegate = self;
        
        FileModel *fileInfo = [self.finishedList objectAtIndex:indexPath.row];
        cell.fileName.text=fileInfo.fileName;
        
        cell.fileSize.text=[CommonHelper getFileSizeString:fileInfo.fileSize];
        cell.fileInfo=fileInfo;
        cell.fileType.text  =[NSString stringWithFormat:@"格式:%@",fileInfo.fileType] ;
        cell.timeLable.text =[NSString stringWithFormat:@"%@",fileInfo.time] ;
        cell.fileImage.image = fileInfo.fileimage;
        cell.playButton.tag = indexPath.row;
        [cell.playButton addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)updateCellOnMainThread:(FileModel *)fileInfo
{
    //    self.bandwithLab.text = [NSString stringWithFormat:@"%@/S",[CommonHelper getFileSizeString:[NSString stringWithFormat:@"%lu",[ASIHTTPRequest averageBandwidthUsedPerSecond]]]] ;
    NSArray *cellArr = [self.downloadingTable visibleCells];
    for(id obj in cellArr)
    {
        if([obj isKindOfClass:[NewDownloadCell class]])
        {
            NewDownloadCell *cell = (NewDownloadCell *)obj;
            if([cell.fileInfo.fileURL isEqualToString: fileInfo.fileURL])
            {
                NSString *currentsize;
                if (fileInfo.post) {
                    currentsize = fileInfo.fileUploadSize;
                    
                }else
                    currentsize = fileInfo.fileReceivedSize;
                NSString *totalsize = [CommonHelper getFileSizeString:fileInfo.fileSize];
                cell.fileCurrentSize.text = [CommonHelper getFileSizeString:currentsize];;
                cell.fileSize.text = [NSString stringWithFormat:@"大小:%@",totalsize];
                cell.sizePercentage.text = [NSString stringWithFormat:@"%@/%@",currentsize,totalsize];
                NSLog(@"cell.sizePercentage.text === %@",cell.sizePercentage.text);
                
                [cell.progressView setProgress:[CommonHelper getProgress:[fileInfo.fileSize floatValue] currentSize:[currentsize floatValue]]];
                NSLog(@"cell.progressView.progress === %f", cell.progressView.progress);
                
                cell.sizePercentage.text = [NSString stringWithFormat:@"%.0f%@", 100 * (cell.progressView.progress), @"%"];
                //                cell.averagebandLab.text =[NSString stringWithFormat:@"%@/s",[CommonHelper getFileSizeString:[NSString stringWithFormat:@"%lu",[ASIHTTPRequest averageBandwidthUsedPerSecond]]]] ;
                if(fileInfo.isDownloading)//文件正在下载
                {
                    [cell.operateButton setBackgroundImage:[UIImage imageNamed:@"下载管理-暂停按钮.png"] forState:UIControlStateNormal];
                }
                else if(!fileInfo.isDownloading && !fileInfo.willDownloading&&!fileInfo.error)
                {
                    [cell.operateButton setBackgroundImage:[UIImage imageNamed:@"下载管理-开始按钮.png"] forState:UIControlStateNormal];
                    cell.sizePercentage.text = @"暂停";
                }else if(!fileInfo.isDownloading && fileInfo.willDownloading&&!fileInfo.error)
                {
                    [cell.operateButton setBackgroundImage:[UIImage imageNamed:@"下载管理-开始按钮.png"] forState:UIControlStateNormal];
                    cell.sizePercentage.text = @"等待";
                }else if (fileInfo.error)
                {
                    [cell.operateButton setBackgroundImage:[UIImage imageNamed:@"下载管理-开始按钮.png"] forState:UIControlStateNormal];
                    cell.sizePercentage.text = @"错误";
                }
            }
        }
    }
}



- (void)startDownload:(ASIHTTPRequest *)request;
{
    NSLog(@"-------开始下载!");
}

- (void)updateCellProgress:(ASIHTTPRequest *)request;
{
    FileModel *fileInfo=[request.userInfo objectForKey:@"File"];
    [self performSelectorOnMainThread:@selector(updateCellOnMainThread:) withObject:fileInfo waitUntilDone:YES];
}

- (void)finishedDownload:(ASIHTTPRequest *)request;
{
    self.diskLabel.text = [CommonHelper getDiskSpaceInfo];
    // [self.downingList removeObject:request];
    [self.downloadingTable reloadData];
//    self.bandwithLab.text = @"0.00K/S";
    [self.finishedTable reloadData];
    
}

- (void)deleteFinishedFile:(FileModel *)selectFile
{
    self.diskLabel.text = [CommonHelper getDiskSpaceInfo];
    self.finishedList = [FilesDownManage sharedFilesDownManage].finishedlist;
    [self.finishedTable reloadData];
}

- (void)ReloadDownLoadingTable
{
    self.downloadingList =[FilesDownManage sharedFilesDownManage].downinglist;
    [self.downloadingTable reloadData];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
